// 存储已下载的视频URL
let downloadedUrls = new Set();
// 下载队列
let downloadQueue = [];
// 是否正在下载
let isDownloading = false;

// 从本地存储加载已下载记录
function loadDownloadHistory() {
  try {
    chrome.storage.local.get('downloadedUrls', function(result) {
      if (result && result.downloadedUrls) {
        downloadedUrls = new Set(result.downloadedUrls);
      }
    });
  } catch (error) {
    console.error('Failed to load download history:', error);
  }
}

// 处理下载队列
function processDownloadQueue() {
  if (isDownloading || downloadQueue.length === 0) {
    return;
  }

  isDownloading = true;
  const url = downloadQueue.shift();
  console.log('开始下载:', url);

  chrome.downloads.download({
    url: url,
    conflictAction: "uniquify",
    saveAs: false
  }, (downloadId) => {
    if (chrome.runtime.lastError) {
      console.error('下载失败:', chrome.runtime.lastError);
      isDownloading = false;
      processDownloadQueue();
    } else if (downloadId) {
      downloadedUrls.add(url);
      chrome.storage.local.set({ 'downloadedUrls': Array.from(downloadedUrls) }, function() {
        if (chrome.runtime.lastError) {
          console.error('保存下载记录失败:', chrome.runtime.lastError);
        } else {
          console.log('已记录下载URL');
        }
      });

      // 监听当前下载完成
      const listener = function(delta) {
        if (delta.id === downloadId && delta.state && delta.state.current === "complete") {
          console.log('视频下载完成');
          chrome.downloads.onChanged.removeListener(listener);
          isDownloading = false;
          processDownloadQueue(); // 处理下一个下载
        }
      };

      chrome.downloads.onChanged.addListener(listener);
    }
  });
}

// 初始化存储
loadDownloadHistory();

chrome.webRequest.onBeforeRequest.addListener(
  function(details) {
    if (details.url.includes('media-video-hvc1')) {
      // 检查是否已下载
      if (downloadedUrls.has(details.url)) {
        console.log('重复视频URL，已跳过:', details.url);
        return { cancel: false };
      }

      // 检查是否已在队列中
      if (!downloadQueue.includes(details.url)) {
        console.log('添加到下载队列:', details.url);
        downloadQueue.push(details.url);
        processDownloadQueue();
      }
    }
  },
  {
    urls: ["*://*/*"],
    types: ["xmlhttprequest", "media"]
  }
);

chrome.downloads.onChanged.addListener(function(delta) {
  if (delta.state && delta.state.current === "complete") {
    console.log('视频下载完成');
  }
});

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === "clearDownloadHistory") {
    downloadedUrls.clear();
    chrome.storage.local.remove("downloadedUrls", function() {
      if (chrome.runtime.lastError) {
        console.error('清除下载记录失败:', chrome.runtime.lastError);
        sendResponse({ status: 'error' });
      } else {
        console.log("下载记录已清除");
        sendResponse({ status: "success" });
      }
    });
    return true;
  } else if (message.action === 'getQueueStatus') {
    sendResponse({
      queueLength: downloadQueue.length,
      isDownloading: isDownloading
    });
  }
});
